<?php
namespace App\Repositories\Attendance;

use App\Exceptions\API\APIException;
use App\Exceptions\API\BadRequest;
use App\Models\Attendance;
use App\Models\User;
use App\Models\WorkTime;
use Illuminate\Pagination\LengthAwarePaginator;

class AttendanceDBRepository implements AttendanceRepository
{

    public function getPaginator(AttendanceFilter $attendanceFilter)
    {
        $attendances = $this->getDBQuery($attendanceFilter);

        $paginator = new LengthAwarePaginator($attendances, $attendances->count(), $attendanceFilter->getPerPage());
        return $paginator;
    }

    protected function getDBQuery(AttendanceFilter $attendanceFilter)
    {

        $workQuery = WorkTime::query();

        //默认为工作日时间
        $workQuery->where('work_type', 1);

        $startTime = $attendanceFilter->getStartTime();
        $endTime = $attendanceFilter->getEndTime();
        if ($startTime && $endTime) {
            $workQuery->where('start_time', '>=', $startTime. ' 00:00:00')
                ->where('start_time', '<=', $endTime. ' 23:00:00');
        }

        if ($workType = $attendanceFilter->getWorkType()) {
            $workQuery->where('work_type', 2);
        }

        $work = $workQuery->get()->toArray();

        $attendances = [];

        foreach ($work as $v) {
            $attendanceQuery = Attendance::query();
            if ($name = $attendanceFilter->getName()) {
                $attendanceQuery->where('name', 'like', '%' . $name . '%');
            }

            if ($departmentName = $attendanceFilter->getDepartmentName()) {
                $attendanceQuery->whereHas('user.department', function ($query) use ($departmentName) {
                    $query->where('name', 'like', '%' . $departmentName . '%');
                });
            }
            if ($userId = $attendanceFilter->getUserId()) {
                $user = User::find($userId);
                $attendanceQuery->where('name',$user->name)->where('attendance_no', $user->attendance_no);
            }

            $res = $attendanceQuery->where('register_time','like', '%'. substr($v['start_time'], 0, 10). '%')->get();
            $defineAttendance = (float)((strtotime($v['end_time'])-strtotime($v['start_time']))%86400/3600);
            $res->groupBy(function ($item) {
                return $item['attendance_no'].'|'.$item['name'];
            })->map(function ($item) use (&$attendances, $defineAttendance){
                $att = new Attendance();
                $sortRes = $item->sortBy('register_time');
                $startTime = $sortRes->first();
                $endTime = $sortRes->pop();

                $att['attendance_no'] = $startTime->attendance_no;
                $att['name'] = $startTime->name;
                $att['department_name'] = User::where('name',$startTime->name)->where('attendance_no', $startTime->attendance_no)->first()->department->name;
                $att['start_time'] = $startTime->register_time;
                $att['end_time'] = $endTime->register_time;
                $minute=(float)((strtotime($att['end_time'])-strtotime($att['start_time']))%86400/3600);
                $att['attendance_time'] = round($minute,1);
                $att['define_attendance_time'] = round($defineAttendance,1);
                $att['percentage'] = round($minute/$defineAttendance*100,1) . '%';
                $attendances[] = $att;
            });
        }


        return collect($attendances);
    }

}
